package com.hbsx.why.utils.updateUtil;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.hbsx.why.R;
import com.hbsx.why.utils.LogUtils;
import com.hbsx.why.utils.NetWorkUtil;
import com.hbsx.why.utils.SDCardUtils;

import java.io.File;
import java.lang.reflect.Method;

/**
 * @author wenjie 版本更新的工具类
 */
public class UpdateVersionUtil {
    public static String APK_NAME = "update.apk";
    public static String VERSIONCODE = "1";
    public static String APK_FILE_NAME = VERSIONCODE + APK_NAME;//CODEZHI
    public static String APK_LOCATION = "/updateVersion/" + APK_FILE_NAME;

    /**
     * 接口回调
     *
     * @author wenjie
     */
    public interface UpdateListener {
        void onUpdateReturned(int updateStatus, VersionInfo versionInfo);
    }

    public UpdateListener updateListener;

    public void setUpdateListener(UpdateListener updateListener) {
        this.updateListener = updateListener;
    }

    /**
     * 网络测试 检测版本
     *
     * @param context 上下文
     */
    public static void netCheckVersion(final Context context, final UpdateListener updateListener) {
        HttpRequest.get("版本更新地址", new HttpRequest.RequestCallBackListener() {

            @Override
            public void onSuccess(String resultData) {
                try {
//					JSONObject jsonObject = JsonUtil.stringToJson(resultData);
//					JSONArray array = jsonObject.getJSONArray("data");
//					VersionInfo mVersionInfo = JsonUtil.jsonToBean(array.getJSONObject(0).toString(), VersionInfo.class);
                    VersionInfo mVersionInfo = null;
                    int clientVersionCode = ApkUtils.getVersionCode(context);
                    int serverVersionCode = mVersionInfo.getVersionCode();
                    //有新版本
                    if (clientVersionCode < serverVersionCode) {
                        int i = NetWorkUtil.checkedNetWorkType(context);
                        if (i == NetWorkUtil.NOWIFI) {
                            updateListener.onUpdateReturned(UpdateStatus.NOWIFI, mVersionInfo);
                        } else if (i == NetWorkUtil.WIFI) {
                            updateListener.onUpdateReturned(UpdateStatus.YES, mVersionInfo);
                        }
                    } else {
                        //无新本
                        updateListener.onUpdateReturned(UpdateStatus.NO, null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    updateListener.onUpdateReturned(UpdateStatus.ERROR, null);
                }
            }

            @Override
            public void onFailure(String error) {
                updateListener.onUpdateReturned(UpdateStatus.TIMEOUT, null);
            }
        });
    }


    /**
     * 本地测试
     */
    public static void localCheckedVersion(final Context context, final UpdateListener updateListener) {
        try {
//			JSONObject jsonObject = JsonUtil.stringToJson(resultData);
//			JSONArray array = jsonObject.getJSONArray("data");
//			VersionInfo mVersionInfo = JsonUtil.jsonToBean(array.getJSONObject(0).toString(), VersionInfo.class);
            VersionInfo mVersionInfo = new VersionInfo();
            mVersionInfo.setDownloadUrl("http://192.168.3.54:8080/APK/app-debug.apk");
            mVersionInfo.setVersionDesc("\n更新内容：\n1、增加xxxxx功能\n2、增加xxxx显示！\n3、用户界面优化！\n4、xxxxxx！\n" +
                    "5、增加xxxxx功能\n" +
                    "6、增加xxxx显示！\n" +
                    "7、用户界面优化！\n" +
                    "8、xxxxxx！\n" +
                    "9、增加xxxxx功能\n" +
                    "10、增加xxxx显示！\n" +
                    "11、用户界面优化！\n" +
                    "12、xxxxxx！");
            mVersionInfo.setVersionCode(2);
            mVersionInfo.setVersionName("v2020");
            mVersionInfo.setVersionSize("1.5M");
            mVersionInfo.setId("1");
            int clientVersionCode = ApkUtils.getVersionCode(context);
            int serverVersionCode = mVersionInfo.getVersionCode();
            //有新版本
            if (clientVersionCode < serverVersionCode) {
                int i = NetWorkUtil.checkedNetWorkType(context);
                if (i == NetWorkUtil.NOWIFI) {
                    updateListener.onUpdateReturned(UpdateStatus.NOWIFI, mVersionInfo);
                } else if (i == NetWorkUtil.WIFI) {
                    updateListener.onUpdateReturned(UpdateStatus.YES, mVersionInfo);
                }
            } else {
                //无新本
                updateListener.onUpdateReturned(UpdateStatus.NO, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateListener.onUpdateReturned(UpdateStatus.ERROR, null);
        }
    }


    /**
     * 弹出新版本提示
     *
     * @param context     上下文
     * @param versionInfo 更新内容
     */
    public static void showDialog(final Context context, final VersionInfo versionInfo) {
        final Dialog dialog = new AlertDialog.Builder(context, R.style.UpdateAppDialog).create();
        APK_FILE_NAME = "" + versionInfo.getVersionCode() + APK_NAME;
        APK_LOCATION = "/updateVersion/" + APK_FILE_NAME;
        final File file = new File(SDCardUtils.getRootDirectory() + APK_LOCATION);
        dialog.setCancelable(true);// 可以用“返回键”取消
        dialog.setCanceledOnTouchOutside(false);//
        dialog.show();
        View view = LayoutInflater.from(context).inflate(R.layout.ui_update_app_dialog, null);
        dialog.setContentView(view);
//		Window window = dialog.getWindow();
//		WindowManager.LayoutParams lp = window.getAttributes();
//		lp.alpha = 1f;
//		window.setAttributes(lp);

        final Button btnOk = (Button) view.findViewById(R.id.btn_ok);
        ImageView btnCancel = (ImageView) view.findViewById(R.id.iv_close);
        TextView tvContent = (TextView) view.findViewById(R.id.tv_update_info);
        TextView tvUpdateTile = (TextView) view.findViewById(R.id.tv_title);
        final TextView tvUpdateMsgSize = (TextView) view.findViewById(R.id.tv_update_msg_size);

        tvContent.setText(versionInfo.getVersionDesc());
        tvUpdateTile.setText("最新版本：" + versionInfo.getVersionName());
        LogUtils.logi("-------APK_FILE_NAME="+APK_FILE_NAME+"<---->APK_LOCATION="+APK_LOCATION);
        if (file.exists() && file.getName().equals(APK_FILE_NAME)) {
            tvUpdateMsgSize.setText("新版本已经下载，是否安装？");
            btnOk.setText("直接安装");
        } else {
            tvUpdateMsgSize.setText("新版本大小：" + versionInfo.getVersionSize());
            btnOk.setText("下载安装");
        }

        btnOk.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                //新版本已经下载
                LogUtils.logi("-------APK_FILE_NAME="+APK_FILE_NAME+"<---->APK_LOCATION="+APK_LOCATION);
                if (file.exists() && file.getName().equals(APK_FILE_NAME)) {
                    Intent intent = ApkUtils.getInstallIntent(file, context);
                    context.startActivity(intent);
                } else {
                    //没有下载，则开启服务下载新版本
                    Intent intent = new Intent(context, UpdateVersionService.class);
                    intent.putExtra("downloadUrl", versionInfo.getDownloadUrl());
                    context.startService(intent);
                }
            }
        });

        btnCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 收起通知栏
     *
     * @param context
     */
    public static void collapseStatusBar(Context context) {
        try {
            Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;
            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
}
